package com.ghsc.ghxc.jsb.ui.home

import android.content.Intent
import android.graphics.Paint
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.config.AppConfig
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.flyco.roundview.RoundLinearLayout
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.api.getUserIdRidUrl
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.FragmentPageRecommendBinding
import com.ghsc.ghxc.jsb.ui.home.activity.EarnIntegralActivity
import com.ghsc.ghxc.jsb.ui.home.activity.GoodsDetailActivity
import com.ghsc.ghxc.jsb.ui.home.activity.WebViewActivity
import com.ghsc.ghxc.jsb.ui.home.adapter.HomeBannerAdapter
import com.ghsc.ghxc.jsb.ui.home.bean.Footcat
import com.ghsc.ghxc.jsb.ui.home.bean.GoodBeanData
import com.ghsc.ghxc.jsb.ui.integral.IntegralSupermarketActivity
import com.ghsc.ghxc.jsb.utils.StringUtil
import com.makeramen.roundedimageview.RoundedImageView
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.youth.banner.indicator.RectangleIndicator

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.home
 * 类名：ListRecommendFragment
 * 创建时间：2024/4/24 14:18
 * 创建人 @author： xiaolin
 * 描述 ：Todo...推荐
 */
class ListRecommendFragment : BaseVMFragment<HomeViewModel, FragmentPageRecommendBinding>(R.layout.fragment_page_recommend){
    override fun attachVMClass(): Class<HomeViewModel>? {
        return HomeViewModel::class.java
    }

    override fun lazyLoad() {

    }
    val config = UserManager.getConfig()
    var index:Int=0
    companion object {
        fun getInstance(index:Int): ListRecommendFragment? {
            var fragment= ListRecommendFragment()
            fragment.index=index
            return fragment
        }
    }
    private val mAdapter: ListAdapter by lazy { ListAdapter() }
    var mList = arrayListOf<GoodBeanData>()
    var footcatName = ""

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.onTabTypeLunBoMethod("")

        binding.rvList.layoutManager = StaggeredGridLayoutManager(2,
            StaggeredGridLayoutManager.VERTICAL)
        binding.rvList.adapter = mAdapter
        mAdapter.setNewInstance(mList)
        initRefreshLayout()
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val bean = mAdapter.data[position]
            loge("position=item="+bean.toString())
            startKtxActivity<GoodsDetailActivity>(
                value =  "pid" to mAdapter.getItem(position).pid
            )
        }

    }

    override fun initData() {
        super.initData()
    }

    override fun initClickListener() {
        super.initClickListener()
        typesAdapter.setOnItemClickListener { adapter, view, position ->
            val bean = typesAdapter.data[position]
            if(bean.cid==4){
                //赚积分
                requireActivity().startKtxActivity<EarnIntegralActivity>()
            }else if(bean.cid==3) {
                //积分超市
//                config?.let {
//                    var sysConfigResultData = it.getWebView()
//                    if(!TextUtils.isEmpty(sysConfigResultData.cfg_value)){
//                        loge("地址="+sysConfigResultData.cfg_value+getUserIdRidUrl())
//                        requireActivity().startKtxActivity<WebViewActivity>(
//                            values = arrayListOf(
//                                "url" to sysConfigResultData.cfg_value+getUserIdRidUrl(),
//                                "showBar" to false,
//                                "title" to sysConfigResultData.cfg_memo,
//                            )
//                        )
//                    }
//                }

                startKtxActivity<IntegralSupermarketActivity>()

            }else if(bean.cid==5) {
                //树拍
                if(!TextUtils.isEmpty(bean.url)){
                    //跳转外部浏览器
                    val uri: Uri = Uri.parse(bean.url)
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(intent)
                }
            }else{
                //商品列表
                footcatName = bean.name
                typesAdapter.data.map {  it.isCheck=false }
                typesAdapter.data[position].isCheck=true
                typesAdapter.notifyDataSetChanged()
                pageNo = 1
                getListData()
            }

        }
    }
    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }
    fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["footcat"] =footcatName
        map["cid"] =""
        map["pindex"] =pageNo
        map["psize"] =pageSize
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGoodsListMethod(it1) }
    }
    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@ListRecommendFragment) {
                showToast(it)
            }
            againLoginMsg.observe(this@ListRecommendFragment) {
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onTabTypeLunBoData.observe(this@ListRecommendFragment) {
                loge("banner==="+it.data.list.size)
                binding.banner.setAdapter(HomeBannerAdapter(it.data.list))
                    .addBannerLifecycleObserver(this@ListRecommendFragment)
                    .indicator = RectangleIndicator(requireActivity())
                binding.banner.setOnBannerListener { data, position ->
                    if (position < it.data.list.size) {
                        val bannerData = it.data.list[position]
                        if (bannerData.ltype == 0) {
                            ///跳转到webview
                            if(!TextUtils.isEmpty(bannerData.url)){
                                if(bannerData.ifexternal==0){
                                    //跳转到webview
                                    requireActivity().startKtxActivity<WebViewActivity>(
                                        values = arrayListOf(
                                            "url" to bannerData.url,
                                            "showBar" to true,
                                            "title" to bannerData.title,
                                        )
                                    )
                                }else{
                                    //跳转外部浏览器
                                    val uri: Uri = Uri.parse(bannerData.url)
                                    val intent = Intent(Intent.ACTION_VIEW, uri)
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                    startActivity(intent)
                                }
                            }
                        }else{
//                            if (bannerData.ltype == 2) {
//                                //图片预览
//                                requireActivity().startKtxActivity<ImgViewActivity>(
//                                    values = arrayListOf(
//                                        "url" to bannerData.url,
//                                    )
//                                )
//                            }
                        }
                    }
                }
                //
                binding.rvTypes.layoutManager = GridLayoutManager(requireActivity(),it.data.data.footcat.size)
                binding.rvTypes.adapter = typesAdapter
                typesAdapter.setNewInstance(it.data.data.footcat)
                footcatName =it.data.data.footcat[0].name
                it.data.data.footcat[0].isCheck=true
                pageNo = 1
                getListData()
            }
            onGoodsListData.observe(this@ListRecommendFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()){
                        mAdapter.replaceData(it.data.list)
                    }
                    else {
                        mAdapter.replaceData(it.data.list)
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }
            }
        }
    }

    private val typesAdapter by lazy { TypesAdapter() }
    inner class TypesAdapter  : BaseQuickAdapter<Footcat, BaseViewHolder>(
        R.layout.layout_page_type) {

        override fun convert(helper: BaseViewHolder, item: Footcat) {
            GlideUtil.ImageLoad(this.context,item.images,helper.getView(R.id.imgIcon))
            helper
                .setText(R.id.tvMenu, item.name)
                .setVisible(R.id.imgCheck,item.isCheck)
        }
    }



    ////商品的adapter
    //屏幕的宽度
    var widthPixels= AppConfig.getApplication().resources.displayMetrics.widthPixels
    //屏幕的密度
    var density= AppConfig.getApplication().resources.displayMetrics.density
    inner class ListAdapter    : BaseQuickAdapter<GoodBeanData, BaseViewHolder>(
        R.layout.layout_home_recommend_item) {
        val width=(widthPixels/density)
        override fun convert(holder: BaseViewHolder, item: GoodBeanData) {
            var llItem= holder.getView<RoundLinearLayout>(R.id.llItem)
            val para1 = llItem.layoutParams
            para1.width = StringUtil.dp2px((width/2)).toInt()  - StringUtil.dp2px(13f).toInt()
            llItem.layoutParams = para1

            val image = holder.getView<RoundedImageView>(R.id.image)
            GlideUtil.ImageLoad(image.context,item.image11,image)
            val img = image.layoutParams
            if (holder.position%2 == 0){
                img.height = StringUtil.dp2px(165f).toInt()
                image.layoutParams=img
            }else{
                img.height = StringUtil.dp2px(180f).toInt()
                image.layoutParams=img
            }
            holder.setText(R.id.tvTitle,item.title)
                .setText(R.id.tvPrice,item.price.toString())
                .setText(R.id.tvOriprice,"￥"+item.oriprice.toString())
            if(!TextUtils.isEmpty(item.oriprice))
            holder.getView<TextView>(R.id.tvOriprice).paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
        }
    }
}